package com.ruoyi.zsyh.controller.applet.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.config.WxConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.wx.WXPayConfig;
import com.ruoyi.common.utils.wx.WXPayRequest;
import com.ruoyi.common.utils.wx.WxAccessToken;
import com.ruoyi.common.utils.wx.WxAccessTokenUtils;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @author yuexl
 */
@Controller
@RequestMapping("/applet/zsyh/wxUser/")
public class WxUserController {

    private Logger logger = LoggerFactory.getLogger(WxUserController.class);

    //小程序的appId
    @Value("${wxconfig.appIdAppletUser}")
    private String appIdApplet;
    //小程序的appSecret
    @Value("${wxconfig.appSecretAppletUser}")
    private String appSecretApplet;

    @Value("${wxconfig.partner}")
    private String partner;

    @Value("${wxconfig.partnerKey}")
    private String partnerKey;

    @Value("${wxconfig.notifyUrlServiceOrderFixdraw}")
    private String notifyUrlServiceOrderFixdraw;

    //公众号的appId
    @Value("${wxconfig.appIdWx}")
    private String appIdWx;
    //公众号的appSecret
    @Value("${wxconfig.appSecretWx}")
    private String appSecretWx;
    //公众号授权回调
    @Value("${wxconfig.authorizationUrlWx}")
    private String authorizationUrlWx;
    //公众号访问的域名
    @Value("${wxconfig.wxQrcodeUrl}")
    private String wxQrcodeUrl;


    @Resource
    private WXPayConfig wxPayConfig;

    @Autowired
    private IZsyhPlatformUserService zsyhPlatformUserService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IZsyhPartsQrcodeApplyService zsyhPartsQrcodeApplyService;

    @Autowired
    private IZsyhUserRepairstoreService zsyhUserRepairstoreService;

    @Autowired
    private IZsyhServiceOrderService zsyhServiceOrderService;

    @Autowired
    private IZsyhServiceOrderCommissionService zsyhServiceOrderCommissionService;

    @Autowired
    private IZsyhServiceSettleService zsyhServiceSettleService;

    @Autowired
    private IZsyhAgentInfoService zsyhAgentInfoService;

    @Autowired
    private IZsyhPlatformFactoryService zsyhPlatformFactoryService;

    @Autowired
    private IZsyhFactoryBalanceDetailsService zsyhFactoryBalanceDetailsService;

    @Autowired
    private WxAccessTokenUtils wxAccessTokenUtils;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IZsyhAgentAreaService zsyhAgentAreaService;

    /**
     * 小程序获取openId 和 session_key
     * https://api.weixin.qq.com/sns/jscode2session?appid=wxc2298573abab5690&secret=2668443994e3d65e93df98223533cf2d&js_code=021UM4ll220fM64hfrll27c8C62UM4lB&grant_type=authorization_code
     * @param response
     */
    @RequestMapping(value = "/appletsLogin")
    @ResponseBody
    public AjaxResult appletsLogin(HttpServletResponse response, HttpServletRequest request)throws Exception {
        String code = request.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appIdApplet+"&secret="+appSecretApplet+"&js_code="+code+"&grant_type=authorization_code";
        String json = UrlUtils.loadURL(url);
        Map<String, Object> wechatToken = JSON.parseObject(json, Map.class);
        String session_key = String.valueOf(wechatToken.get("session_key"));
        String openid = String.valueOf(wechatToken.get("openid"));
        logger.info("code-----------------------" + code);
        logger.info("session_key-----------------------" + session_key);
        logger.info("openid-----------------------" + openid);

        ZsyhPlatformUser  user = zsyhPlatformUserService.selectZsyhPlatformUserByOpenId(openid);
        if(user != null){
            ZsyhPlatformUser user1 = new ZsyhPlatformUser();
            user1.setId(user.getId());
            wechatToken.put("id", user.getId());
            wechatToken.put("phone", user.getUserPhone());
            wechatToken.put("userType", user.getUserType());
//            String isAppraisal = "0";
//            String isCity = "0";
//            ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(user.getId());
//            if(EmptyUtils.isNotEmpty(store)){
//                isAppraisal = store.getIsAppraisal();
//            }
//            if(store != null && "2".equals(store.getStoreState())){//网点
//                user1.setIsCity("1");
//                zsyhPlatformUserService.updateZsyhPlatformUser(user1);
//                isCity = "1";
//            }
            wechatToken.put("appraisal", user.getIsAppraisal());
            wechatToken.put("isCity", user.getIsCity());
            return AjaxResult.success("操作成功", wechatToken);
        }
        return AjaxResult.error("openId不存在");
    }


    /**
     * 小程序获取openId 和 session_key
     * 用户授权获取手机号
     * https://api.weixin.qq.com/sns/jscode2session?appid=wxc2298573abab5690&secret=2668443994e3d65e93df98223533cf2d&js_code=021UM4ll220fM64hfrll27c8C62UM4lB&grant_type=authorization_code
     * @param response
     */
    @RequestMapping(value = "/appletsLoginPhone")
    @ResponseBody
    public AjaxResult appletsLoginPhone(HttpServletResponse response, HttpServletRequest request)throws Exception {
        String code = request.getParameter("code");
        String encryptDataB64 = request.getParameter("encryptDataB64");//包括敏感数据在内的完整用户信息的加密数据
        String ivB64 = request.getParameter("ivB64");//加密算法的初始向量
        if(EmptyUtils.isEmpty(code) || EmptyUtils.isEmpty(encryptDataB64) || EmptyUtils.isEmpty(ivB64)){
            return AjaxResult.error("信息不足，获取手机号失败，请重新授权");
        }

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appIdApplet+"&secret="+appSecretApplet+"&js_code="+code+"&grant_type=authorization_code";
        logger.info("url====================================" + url);
        String json = UrlUtils.loadURL(url);
        logger.info("json====================================" + json);
        Map<String, Object> wechatToken = JSON.parseObject(json, Map.class);
        String session_key = String.valueOf(wechatToken.get("session_key"));
        String openid = String.valueOf(wechatToken.get("openid"));
        if(EmptyUtils.isEmpty(openid)){
            return AjaxResult.error("授权失败，请重新授权");
        }
        logger.info("code====================================" + code);
        logger.info("encryptDataB64====================================" + encryptDataB64);
        logger.info("ivB64====================================" + ivB64);
        logger.info("session_key====================================" + session_key);
        logger.info("openid====================================" + openid);
        logger.info("code-----------------------" + code);
        logger.info("encryptDataB64-----------------------" + encryptDataB64);
        logger.info("ivB64-----------------------" + ivB64);
        logger.info("session_key-----------------------" + session_key);
        logger.info("openid-----------------------" + openid);
        encryptDataB64 = encryptDataB64.replaceAll(" ", "+");
        ivB64 = ivB64.replaceAll(" ", "+");

        logger.info("encryptDataB64-----------------------" + encryptDataB64);
        logger.info("ivB64-----------------------" + ivB64);
        logger.info("encryptDataB64====================================" + encryptDataB64);
        logger.info("ivB64====================================" + ivB64);
//        ZsyhUserAddress user = zsyhUserAddressService.selectZsyhUserAddressByOpenId(openid);
//        if(user != null){
//            wechatToken.put("id", user.getId());
//            wechatToken.put("phone", user.getUserPhone());
//        }else{
        String phoneJson = WechatDecryptDataUtil.decryptData(encryptDataB64, session_key, ivB64);
        logger.info("phoneJson====================================" + phoneJson);
        Map<String, Object> _phoneJson = JSON.parseObject(phoneJson, Map.class);
        String phone = String.valueOf(_phoneJson.get("phoneNumber"));
//        String nickname = String.valueOf(_phoneJson.get("phoneNumber"));//昵称
//        String imgUrl = String.valueOf(_phoneJson.get("avatarUrl"));//头像
        if(EmptyUtils.isNotEmpty(phone)){

            ZsyhPlatformUser  user = zsyhPlatformUserService.selectZsyhPlatformUserByPhone(phone);
            if(user != null){

                ZsyhPlatformUser user1 = new ZsyhPlatformUser();
                user1.setId(user.getId());
                user1.setUserOpenid(openid);
//                user1.setUserType("2");//用户类型（1普通客户2维修师傅）
//                user1.setUserWximage(imgUrl);
//                user1.setUserNickname(nickname);
                wechatToken.put("id", user.getId());
                wechatToken.put("userType", user.getUserType());
                wechatToken.put("appraisal", user.getIsAppraisal());
                wechatToken.put("isCity", user.getIsCity());
                zsyhPlatformUserService.updateZsyhPlatformUser(user1);
//                //判断师傅信息师傅存在，不存在，添加师傅信息 zsyh_user_store
//                ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(user.getId());
//                if(EmptyUtils.isEmpty(store)){
//                    store = new ZsyhUserRepairstore();
//                    store.setId(IdWorker.getId());
//                    store.setUserId(user.getId());
//
//                    //如果是网点 则添加isRaker
//                    if("1".equals(user.getIsCity())){
//                        store.setIsRaker("1");
//                        store.setStoreState("2");//网点 状态（0未申请 1待审核 2通过 3驳回）
//                    }
//                    //如果是鉴定点 添加
//                    if("1".equals(user.getIsAppraisal())){
//                        store.setIsAppraisal("1");
//                        store.setAppraisalState("2");//鉴定点 状态（0未申请 1待审核 2通过 3驳回）
//                    }
//                    String qrCodeImg = postMiniqrQr(store.getId(), "1");
//                    store.setQrcodeImg(qrCodeImg);
//
//                    zsyhUserRepairstoreService.insertZsyhUserRepairstoreApplet(store);
//                }

            }else{//手机号不存在，保存客户信息
                String id = IdWorker.getId();
                ZsyhPlatformUser user1 = new ZsyhPlatformUser();
                user1.setId(id);
                user1.setUserPhone(phone);
                user1.setCreateTime(new Date());
                user1.setUserOpenid(openid);
//                user1.setUserWximage(imgUrl);
//                user1.setUserNickname(nickname);
                user1.setUserType("1");//用户类型（1普通客户2维修师傅）
                zsyhPlatformUserService.insertZsyhPlatformUser(user1);

//                //添加师傅信息 zsyh_user_store
//                ZsyhUserRepairstore store = new ZsyhUserRepairstore();
//                store.setId(IdWorker.getId());
//                store.setUserId(user.getId());
//                String qrCodeImg = postMiniqrQr(store.getId(), "1");
//                store.setQrcodeImg(qrCodeImg);
//                zsyhUserRepairstoreService.insertZsyhUserRepairstoreApplet(store);


                wechatToken.put("id", id);
                wechatToken.put("userType", user1.getUserType());
                wechatToken.put("appraisal", "0");
                wechatToken.put("isCity", "0");
            }
        }else{
            String id = IdWorker.getId();
            Random random = new Random();
            String YZCode = "";
            for (int i = 0; i < 6; i++) {
                YZCode += random.nextInt(10);
            }
            ZsyhPlatformUser user1 = new ZsyhPlatformUser();
            user1.setId(id);
            user1.setUserPhone("13949"+YZCode);
            user1.setCreateTime(new Date());
            user1.setUserOpenid(openid);
            user1.setUserWximage("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");
            user1.setUserNickname("微信用户");
            user1.setUserType("1");//用户类型（1普通客户2维修师傅）
            zsyhPlatformUserService.insertZsyhPlatformUser(user1);

//            //添加师傅信息 zsyh_user_store
//            ZsyhUserRepairstore store = new ZsyhUserRepairstore();
//            store.setId(IdWorker.getId());
//            store.setUserId(user1.getId());
//            String qrCodeImg = postMiniqrQr(store.getId(), "1");
//            store.setQrcodeImg(qrCodeImg);
//            zsyhUserRepairstoreService.insertZsyhUserRepairstoreApplet(store);

            wechatToken.put("id", id);
            wechatToken.put("userType", user1.getUserType());
            wechatToken.put("appraisal", "0");
            wechatToken.put("isCity", "0");
            phone = user1.getUserPhone();
        }

        wechatToken.put("phone", phone);
        logger.info("wechatToken====================================" + wechatToken);
        return AjaxResult.success("操作成功", wechatToken);
    }


    /**
     * 用户授权获取头像昵称
     * @param response
     */
    @RequestMapping(value = "/saveAppletsInformation")
    @ResponseBody
    public AjaxResult saveAppletsInformation(HttpServletResponse response, HttpServletRequest request)throws Exception {
        String code = request.getParameter("code");
        String nickname = request.getParameter("nickname");//昵称
        String imgUrl = request.getParameter("imgUrl");//头像
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appIdApplet+"&secret="+appSecretApplet+"&js_code="+code+"&grant_type=authorization_code";
        logger.info("url====================================" + url);
        String json = UrlUtils.loadURL(url);
        logger.info("json====================================" + json);
        Map<String, Object> wechatToken = JSON.parseObject(json, Map.class);
        String session_key = String.valueOf(wechatToken.get("session_key"));
        String openid = String.valueOf(wechatToken.get("openid"));

        ZsyhPlatformUser  user = zsyhPlatformUserService.selectZsyhPlatformUserByOpenId(openid);
        if(user != null){
            ZsyhPlatformUser user1 = new ZsyhPlatformUser();
            user1.setId(user.getId());
            user1.setUserWximage(imgUrl);
            user1.setUserNickname(nickname);
            zsyhPlatformUserService.updateZsyhPlatformUser(user1);
        }

        return AjaxResult.success("操作成功", wechatToken);
    }

    /**
     * 保存头像和昵称
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/saveInformation")
    @ResponseBody
    public AjaxResult saveInformation(HttpServletRequest request)throws Exception {
        String nickname = request.getParameter("nickname");//昵称
        String imgUrl = request.getParameter("imgUrl");//头像
        String userId = request.getParameter("userId");//用户id
        ZsyhPlatformUser user = new ZsyhPlatformUser();
        user.setId(userId);
        user.setUserWximage(imgUrl);
        user.setUserNickname(nickname);
        zsyhPlatformUserService.updateZsyhPlatformUser(user);
        return AjaxResult.success("操作成功");
    }


    /**
     * 小程序获取openId 和 session_key
     * 用户授权获取手机号
     * https://api.weixin.qq.com/sns/jscode2session?appid=wxc2298573abab5690&secret=2668443994e3d65e93df98223533cf2d&js_code=021UM4ll220fM64hfrll27c8C62UM4lB&grant_type=authorization_code
     */
    @RequestMapping(value = "/wechat/test")
    @ResponseBody
    public AjaxResult test()throws Exception {
//        //封装参数
        String scene = "1026558882538852352";//带参
        String img = postMiniqrQr(scene, "1");
        System.out.println(img);
        return AjaxResult.success(img);
//        return AjaxResult.success("操作成功", updateStoreWxImage());
    }

    /**
     * 生成带参小程序二维码
     * @param scene	要输入的内容
     * @param  type 店铺类型（1维修店2配件店3电器店）
     */
    public String postMiniqrQr(String scene, String type) {
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appIdApplet+"&secret="+appSecretApplet;
        String json = UrlUtils.loadURL(tokenUrl);
        Map<String, Object> wechatToken = JSON.parseObject(json, Map.class);
        String access_token = String.valueOf(wechatToken.get("access_token"));
        logger.info("access_token-----------------------" + access_token);

        String imgName = scene + ".png";
        String imgUrl = serverConfig.getUrl() + "/profile/upload/store/qrCode/" +  imgName;
        try{
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token);
//            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacode?access_token="+access_token);//少量的
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true); // 打开写入属性
            httpURLConnection.setDoInput(true); // 打开读取属性
            httpURLConnection.setRequestMethod("POST");// 提交方式
            // 不得不说一下这个提交方式转换！！真的坑。。改了好长时间！！一定要记得加响应头
            httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");// 设置响应头
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
//            Map map = new HashMap();
//            map.put("r", 255);
//            map.put("g", 246);
//            map.put("b", 229);
            String page = "pages/shopNear/detail/detail2";
            if("1".equals(type)){
                page = "pages/shopNear/detail/detail1";
            }
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", scene); // 你要放的内容
            paramJson.put("page", page);
            paramJson.put("env_version", "release"); // 要打开的小程序版本。正式版为 release，体验版为 trial，开发版为 develop
//            paramJson.put("path", "pages/shopNear/detail/detail1?id=1026558882538852352");
            paramJson.put("width", 430); // 宽度
            paramJson.put("auto_color", true);
            paramJson.put("is_hyaline", false);
//            paramJson.put("line_color", map);
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();

            // 如果没有该路径，那么创建一个
            File file = new File(filePath + "/store/qrCode");
            if (!file.exists()){
                file.mkdirs();
            }
            //创建一个空文件
            OutputStream os = new FileOutputStream(new File(filePath + "/store/qrCode/" + imgName));
            //ByteArrayOutputStream os = new ByteArrayOutputStream();
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1)
            {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
            // 上传云储存
            //InputStream is = new ByteArrayInputStream(os.toByteArray());
            //retMap = UploadUtils.upload(is);

//            File file1 = new File(filePath + imgName);
//            imgBase64 = Base64.getEncoder().encodeToString(fileToByte(file1));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return imgUrl;
    }


    /**
     * 跟新店铺带参二维码
     * @return
     */
    public List updateStoreWxImage() {
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appIdApplet+"&secret="+appSecretApplet;
        String json = UrlUtils.loadURL(tokenUrl);
        Map<String, Object> wechatToken = JSON.parseObject(json, Map.class);
        String access_token = String.valueOf(wechatToken.get("access_token"));
        logger.info("access_token-----------------------" + access_token);

        List<ZsyhUserRepairstore> list = zsyhUserRepairstoreService.selectZsyhUserRepairstoreList(new ZsyhUserRepairstore());
        List<String> imgUrlList = new ArrayList<>();
        for(ZsyhUserRepairstore a:list){
            String storeClassify = a.getStoreClassify();//店铺类型（1维修店2配件店3电器店）
            String page = "pages/shopNear/detail/detail2";
            if("1".equals(storeClassify)){
                page = "pages/shopNear/detail/detail1";
            }
            String id = a.getId();

            String imgName = id + ".png";
            String imgUrl = serverConfig.getUrl() + "/profile/upload/store/qrCode/" +  imgName;
            try{
                URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token);
//            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacode?access_token="+access_token);//少量的
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                // conn.setConnectTimeout(10000);//连接超时 单位毫秒
                // conn.setReadTimeout(2000);//读取超时 单位毫秒
                // 发送POST请求必须设置如下两行
                httpURLConnection.setDoOutput(true); // 打开写入属性
                httpURLConnection.setDoInput(true); // 打开读取属性
                httpURLConnection.setRequestMethod("POST");// 提交方式
                // 不得不说一下这个提交方式转换！！真的坑。。改了好长时间！！一定要记得加响应头
                httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");// 设置响应头
                // 获取URLConnection对象对应的输出流
                PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
//            Map map = new HashMap();
//            map.put("r", 255);
//            map.put("g", 246);
//            map.put("b", 229);

                // 发送请求参数
                JSONObject paramJson = new JSONObject();
                paramJson.put("scene", id); // 你要放的内容
                paramJson.put("page", page);
                paramJson.put("env_version", "release"); // 要打开的小程序版本。正式版为 release，体验版为 trial，开发版为 develop
//            paramJson.put("path", "pages/shopNear/detail/detail1?id=1026558882538852352");
                paramJson.put("width", 430); // 宽度
                paramJson.put("auto_color", true);
                paramJson.put("is_hyaline", false);
//            paramJson.put("line_color", map);
                printWriter.write(paramJson.toString());
                // flush输出流的缓冲
                printWriter.flush();
                BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();

                // 如果没有该路径，那么创建一个
                File file = new File(filePath + "/store/qrCode");
                if (!file.exists()){
                    file.mkdirs();
                }
                //创建一个空文件
                OutputStream os = new FileOutputStream(new File(filePath + "/store/qrCode/" + imgName));
                //ByteArrayOutputStream os = new ByteArrayOutputStream();
                int len;
                byte[] arr = new byte[1024];
                while ((len = bis.read(arr)) != -1)
                {
                    os.write(arr, 0, len);
                    os.flush();
                }
                os.close();
                // 上传云储存
                //InputStream is = new ByteArrayInputStream(os.toByteArray());
                //retMap = UploadUtils.upload(is);

//            File file1 = new File(filePath + imgName);
//            imgBase64 = Base64.getEncoder().encodeToString(fileToByte(file1));
                ZsyhUserRepairstore store = new ZsyhUserRepairstore();
                store.setId(id);
                store.setQrcodeImg(imgUrl);
                zsyhUserRepairstoreService.updateZsyhUserRepairstoreApplet(store);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            imgUrlList.add(imgUrl);
        }
        return imgUrlList;
    }

    /**
     * 文件File类型转byte[]
     *
     * @param file
     * @return
     */
    public static byte[] fileToByte(File file) {
        byte[] fileBytes = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            fileBytes = new byte[(int) file.length()];
            fis.read(fileBytes);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileBytes;
    }

    /**
     * 核销补助金申请
     * @param applyId
     * @param userId
     * @param extractionCode
     * @return
     * @throws Exception
     */
    @RequestMapping("/writeOffAndAppropriationQrCodeApply")
    @ResponseBody
    @Transactional
    public AjaxResult writeOffAndAppropriationQrCodeApply(String applyId, String userId, String extractionCode)throws Exception{
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String repairId = store.getId();

        ZsyhPartsQrcodeApply apply = zsyhPartsQrcodeApplyService.selectZsyhPartsQrcodeApplyById(applyId);
        if(!repairId.equals(apply.getStoreId())){
            return AjaxResult.error("不是您鉴定的配件，您无权核销");
        }
        if(!extractionCode.equals(apply.getExtractionCode())){
            return AjaxResult.error("核销码不正确");
        }
        if("6".equals(apply.getApplyStatus()) || "7".equals(apply.getApplyStatus()) || "2".equals(apply.getIsTransfer())){
            return AjaxResult.error("已核销拨款，请勿重复操作");
        }
        BigDecimal factoryBalance = apply.getFactoryBalance();//厂家余额
        BigDecimal factoryMoney = apply.getFactoryMoney();//厂家保证金

        if(factoryBalance.doubleValue() < apply.getPayPrice().doubleValue() && factoryMoney.doubleValue() < apply.getPayPrice().doubleValue() ){
            return AjaxResult.error("厂家赔付金额不足，请联系客服");
        }

        ZsyhPartsQrcodeApply apply1 = new ZsyhPartsQrcodeApply();
        apply1.setId(applyId);
        apply1.setIsTransfer("2");
        apply1.setApplyStatus("7");
        apply1.setTransferTime(new Date());
        apply1.setTransferPerson(userId);


        ZsyhPlatformUser user = zsyhPlatformUserService.selectZsyhPlatformUserById(userId);
        String openId = user.getUserOpenid();


        Map<String, String> m = new HashMap<>();
        m.put("openid",openId);
        m.put("orderId",applyId);
        m.put("money",apply.getPayPrice().toString());
//        m.put("money","0.3");//测试金额
        m.put("spbillCreateIp","127.0.0.1");


        Map<String, Object> responseMap = null;
        //暂时屏蔽付款 TODO
        responseMap = sendPayBZJ(m);
        zsyhPartsQrcodeApplyService.updateZsyhPartsQrcodeApply(apply1);

        if(responseMap != null && responseMap.size() > 0){
            if("SUCCESS".equals(responseMap.get("result_code").toString())){
                String paymentNo = responseMap.get("payment_no").toString();
                logger.info("调用成功");
                //调用成功，修改申请状态，转账状态
                apply1.setPaymentNo(paymentNo);
                zsyhPartsQrcodeApplyService.updateZsyhPartsQrcodeApply(apply1);

                //修改厂家余额
                ZsyhPlatformFactory factory = new ZsyhPlatformFactory();
                String factoryId = apply.getFactoryId();
                factory.setId(factoryId);

                ZsyhFactoryBalanceDetails details = new ZsyhFactoryBalanceDetails();
                details.setFactoryId(factoryId);
                details.setFactoryMoney(apply.getPayPrice());
                details.setFactoryType("4");
                details.setFactoryOrderNum(applyId);

                if(factoryBalance.doubleValue() >= apply.getPayPrice().doubleValue()){
                    factory.setFactoryBalance(factoryBalance.subtract(apply.getPayPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    details.setFactoryClassify("2");
                    details.setFactoryBalance(factory.getFactoryBalance());
                }else{
                    factory.setFactoryMoney(factoryMoney.subtract(apply.getPayPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    details.setFactoryClassify("1");
                    details.setFactoryBalance(factory.getFactoryMoney());
                }
                zsyhPlatformFactoryService.updateZsyhPlatformFactory(factory);
                //添加交易明细
                zsyhFactoryBalanceDetailsService.insertZsyhFactoryBalanceDetails(details);

                return AjaxResult.success("操作成功");
            }else{
                String err_code = responseMap.get("err_code").toString();
                String msg = "操作失败";
                switch (err_code){
                    case "AMOUNT_LIMIT":msg += ",金额超限!";break;
                    case "NOTENOUGH":msg += ",您的付款帐号余额不足或资金未到账!";break;
                    case "SYSTEMERROR":msg += ",系统繁忙，请稍后再试!";break;
                    case "V2_ACCOUNT_SIMPLE_BAN":msg += ",用户微信支付账户未知名，无法付款!";break;
                    case "SENDNUM_LIMIT":msg += ",该用户今日付款次数超过限制,如有需要请登录微信支付商户平台更改API安全配置!";break;
                    case "MONEY_LIMIT":msg += ",已经达到今日付款总额上限/已达到付款给此用户额度上限!";break;
                    case "FREQ_LIMIT":msg += ",超过频率限制，请稍后再试!";break;
                    default:break;
                }
                return AjaxResult.error(msg);
            }
        }
        return AjaxResult.success("成功");
    }

    /**
     * 维修工补助金转账
     * @param m
     * @return
     * @throws Exception
     */
    public Map<String, Object> sendPayBZJ(Map<String, String> m)throws Exception {

        String openId = m.get("openid");
        // 1 参数
        // 订单号
        String orderId = m.get("orderId");
        // 总金额以分为单位，不带小数点
        String totalFee = StringUtils.getMoney(m.get("money"));

        // 订单生成的机器 IP
        String spbill_create_ip = m.get("spbillCreateIp");

        // ---必须参数
        // 商户号
        String mch_id = partner;
        // 随机字符串
        String nonce_str = StringUtils.getNonceStr();

        String desc = "侯保配件-补助金";

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("mch_appid", appIdApplet);
        packageParams.put("mchid", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("desc", desc);
        packageParams.put("partner_trade_no", orderId);
        // 这里写的金额为1 分到时修改
        packageParams.put("amount", totalFee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("check_name", "NO_CHECK");
        packageParams.put("openid", openId);

        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(appIdApplet, appSecretApplet, partnerKey);

        String sign = reqHandler.createSign(packageParams);
        logger.info("第一次签名------------------------------" + sign);
        logger.info("第一次签名------------------------------" + sign);
        String xml = "<xml>" + "<mch_appid>" + appIdApplet + "</mch_appid>" + "<mchid>"
                + mch_id + "</mchid>" + "<nonce_str>" + nonce_str
                + "</nonce_str>"
                + "<partner_trade_no>" + orderId + "</partner_trade_no>"
                + "<openid>" + openId + "</openid>"
                + "<check_name>NO_CHECK</check_name>"
                + "<amount>" + totalFee + "</amount>"
                + "<desc>"+ desc +"</desc>"
                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                + "<sign>" + sign + "</sign>"
                + "</xml>";
        String createOrderURL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";


        Map<String, Object> map = new GetWxOrderno().sendPost(createOrderURL, xml);
        logger.info("info---------------------------------------------------------获取到的预支付ID：" + map);
        logger.info("获取到的预支付ID：" + map);

        return map;
    }



    /**
     * 维修师傅缴纳固定抽成费用
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/wxPayServiceOrderFixdraw")
    public AjaxResult wxPayServiceOrderFixdraw(String userId, String orderId, HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        ZsyhServiceOrder order = zsyhServiceOrderService.selectZsyhServiceOrderById(orderId);
        ZsyhPlatformUser user = zsyhPlatformUserService.selectZsyhPlatformUserById(userId);
        String openId = user.getUserOpenid();
        //更改钱数
        String totalfee = order.getOrderFixdraw().toString();
//        String totalfee = "0.01";
        List<Map<String, Object>> commlist = new ArrayList<Map<String, Object>>();
        Map<String, Object> resultmap = new HashMap<String, Object>();
        //微信支付jsApi
        logger.info(openId);
        WxPayDto tpWxPay = new WxPayDto();
        tpWxPay.setOpenId(openId);
        tpWxPay.setBody("服务订单费用");
        tpWxPay.setOrderId(orderId + StringUtils.getRandomCode());
        tpWxPay.setSpbillCreateIp("127.0.0.1");
        tpWxPay.setTotalFee(totalfee);
        tpWxPay.setAttach(orderId);

        String returnresult = getPackageApplets(tpWxPay);
        logger.info(returnresult);
        String[] resultarray = returnresult.split(",");
        for (String item : resultarray) {
            String[] temp = item.split(":");
            logger.info("item" + item);
            logger.info("temp[0]" + temp[0] + "temp[1]" + temp[1]);
            temp[0] = temp[0].replaceAll("\"", "");
            temp[1] = temp[1].replaceAll("\"", "");
            resultmap.put(temp[0], temp[1]);
        }
        commlist.add(resultmap);
        JSONArray json = JSONArray.fromObject(commlist);
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream out = response.getOutputStream();
        //out.print(callback + "(" + json + ")");

        logger.info("json**********" + json + "***************");
//        logger.info("callback"+callback+"*********************after");
        return AjaxResult.success(json);
    }


    /**
     * 小程序支付回调  固定抽成
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/repairNotifyServiceOrderFixdraw", method = RequestMethod.POST)
    @ResponseBody
    public String repairNotifyServiceOrderFixdraw(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        WXPayRequest wxPayRequest = new WXPayRequest(this.wxPayConfig);
        Map<String, String> result = new HashMap<String, String>();
        Map<String, String> params = null;
        String returnxml = "";
        InputStream inputStream;
        StringBuffer sb = new StringBuffer();
        //以字节流的形式读取request中的数据
        inputStream = request.getInputStream();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((s = in.readLine()) != null) {
            sb.append(s);
        }
        in.close();
        inputStream.close();
        params = WXPayUtil.xmlToMap(sb.toString());
        logger.info("1.notify-params>>>>>>>>>>>:" + params);

        String returnCode = params.get("return_code");
        logger.info("3.returnCode:" + returnCode);
        if (returnCode.equals("SUCCESS")) {
            //判断签名是否正确
            boolean flag = wxPayRequest.isResponseSignatureValid(params, partnerKey);
            logger.info("2.notify-flag:" + flag);
            if (flag) {
                //获取微信订单号
                String transactionId = params.get("transaction_id");
                //获取商户订单号
                String outTradeNo = params.get("out_trade_no");

                String total_fee = params.get("total_fee");//支付金额

                //附加信息原路返回 订单id
                String attach = params.get("attach");

                logger.info("transactionId====================================" + transactionId);
                logger.info("outTradeNo====================================" + outTradeNo);
                logger.info("attach====================================" + attach);
                logger.info("total_fee====================================" + total_fee);
                outTradeNo = outTradeNo.substring(0, outTradeNo.length()-6);
                logger.info("outTradeNo====================================" + outTradeNo);
                ZsyhServiceOrder order = zsyhServiceOrderService.selectZsyhServiceOrderById(attach);
                String agentId = order.getAgentId();
                String rakerId = order.getRakerId();
                String orderFixdrawState = order.getOrderFixdrawState();
                //抽成费用未支付的状态下执行
                if("0".equals(orderFixdrawState)){
                    //TODO 固定抽成费用支付成功 分配给省级，市县级
                    BigDecimal totalFee = new BigDecimal(total_fee).multiply(new BigDecimal("0.01")).setScale(2, BigDecimal.ROUND_HALF_UP);
//                    BigDecimal totalFee = new BigDecimal("20");
//                    BigDecimal tax = totalFee.multiply(new BigDecimal("0.006"));
                    BigDecimal agentMoney = BigDecimal.ZERO;
                    BigDecimal rakerMoney = BigDecimal.ZERO;
                    if(EmptyUtils.isNotEmpty(agentId)){//会长分成0.2
                        agentMoney = totalFee.multiply(new BigDecimal("0.2"));
                    }
                    if(EmptyUtils.isNotEmpty(rakerId)){//市县分成0.3
                        rakerMoney = totalFee.multiply(new BigDecimal("0.3"));
                    }

                    //修改支付状态
                    ZsyhServiceOrder order1 = new ZsyhServiceOrder();
                    order1.setId(attach);
                    order1.setOrderFixdrawState("1");
                    zsyhServiceOrderService.updateZsyhServiceOrder(order1);

                    //保存会长，市县收益提成
                    ZsyhServiceOrderCommission commission = new ZsyhServiceOrderCommission();
                    commission.setId(IdWorker.getId());
                    commission.setOrderId(attach);
                    commission.setAgentId(agentId);
                    commission.setRakerId(rakerId);
                    commission.setAgentCommission(agentMoney.setScale(2, BigDecimal.ROUND_HALF_UP));
                    commission.setRakerCommission(rakerMoney.setScale(2, BigDecimal.ROUND_HALF_UP));
                    commission.setTaxMoney(BigDecimal.ZERO);
                    commission.setOrderFixdraw(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP));
                    zsyhServiceOrderCommissionService.insertZsyhServiceOrderCommission(commission);


                    String agentOpenId = "", rakerOpenId = "";
                    String dateString = DateUtils.getDate();
                    Integer year = Integer.valueOf(dateString.substring(0,4));
                    Integer month = Integer.valueOf(dateString.substring(5,7));
                    if(EmptyUtils.isNotEmpty(agentId)){
                        ZsyhAgentInfo agentInfo = zsyhAgentInfoService.selectZsyhAgentInfoById(agentId);
                        if(EmptyUtils.isNotEmpty(agentInfo)){
                            agentOpenId = agentInfo.getAgentOpenid();

                            ZsyhServiceSettle serviceSettle = new ZsyhServiceSettle();
                            serviceSettle.setAgentId(agentId);
                            serviceSettle.setPeriodYear(year);
                            serviceSettle.setPeriodMonth(month);
                            List<ZsyhServiceSettle> list = zsyhServiceSettleService.selectZsyhServiceSettleList(serviceSettle);
                            if(list.size() == 0){
                                serviceSettle.setAgentOpenid(agentOpenId);
                                serviceSettle.setId(IdWorker.getId());
                                serviceSettle.setAgentSettleMoney(agentMoney.setScale(2, BigDecimal.ROUND_HALF_UP));
                                serviceSettle.setSettleStatue("1");
                                serviceSettle.setSettleType("1");
                                zsyhServiceSettleService.insertZsyhServiceSettle(serviceSettle);
                            }else{
                                ZsyhServiceSettle serviceSettle1 = list.get(0);
                                serviceSettle.setId(serviceSettle1.getId());
                                serviceSettle.setAgentSettleMoney((serviceSettle1.getAgentSettleMoney().add(agentMoney)).setScale(2, BigDecimal.ROUND_HALF_UP));
                                zsyhServiceSettleService.updateZsyhServiceSettle(serviceSettle);
                            }

                        }
                    }
                    if(EmptyUtils.isNotEmpty(rakerId)){
                        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreById(rakerId);
                        if(store != null){
                            String userId = store.getUserId();
                            ZsyhPlatformUser user = zsyhPlatformUserService.selectZsyhPlatformUserById(userId);
                            rakerOpenId = user.getUserOpenid();

                            ZsyhServiceSettle serviceSettle = new ZsyhServiceSettle();
                            serviceSettle.setRakerId(rakerId);
                            serviceSettle.setPeriodYear(year);
                            serviceSettle.setPeriodMonth(month);
                            List<ZsyhServiceSettle> list = zsyhServiceSettleService.selectZsyhServiceSettleList(serviceSettle);
                            if(list.size() == 0){
                                serviceSettle.setRakerOpenid(rakerOpenId);
                                serviceSettle.setId(IdWorker.getId());
                                serviceSettle.setRakerSettleMoney(rakerMoney.setScale(2, BigDecimal.ROUND_HALF_UP));
                                serviceSettle.setSettleStatue("1");
                                serviceSettle.setSettleType("2");
                                zsyhServiceSettleService.insertZsyhServiceSettle(serviceSettle);
                            }else{
                                ZsyhServiceSettle serviceSettle1 = list.get(0);
                                serviceSettle.setId(serviceSettle1.getId());
                                serviceSettle.setRakerSettleMoney((serviceSettle1.getRakerSettleMoney().add(agentMoney)).setScale(2, BigDecimal.ROUND_HALF_UP));
                                zsyhServiceSettleService.updateZsyhServiceSettle(serviceSettle);
                            }
                        }
                    }
                }
                result.put("return_code", "SUCCESS");
                result.put("return_msg", "支付成功");
                logger.info("4.订单：" + outTradeNo + " 交易完成" + ">>>" + transactionId);
            } else {
                result.put("return_code", "FAIL");
                result.put("return_msg", "签名失败");
                logger.info("签名验证失败>>>>>>>>>>>>");
            }
        } else {
            result.put("return_code", "FAIL");
            result.put("return_msg", "支付失败");
            logger.info("");
        }


        returnxml = WXPayUtil.mapToXml(result);
        return returnxml;
    }



    /**
     * 获取请求预支付id报文
     * 维修师傅缴纳固定抽成
     * @return
     */
    @SuppressWarnings("static-access")
    public String getPackageApplets(WxPayDto tpWxPayDto) {

        String openId = tpWxPayDto.getOpenId();
        // 1 参数
        // 订单号
        String orderId = tpWxPayDto.getOrderId();
        // 附加数据 原样返回
        String attach = tpWxPayDto.getAttach();
        // 总金额以分为单位，不带小数点
        String totalFee = StringUtils.getMoney(tpWxPayDto.getTotalFee());

        // 订单生成的机器 IP
        String spbill_create_ip = tpWxPayDto.getSpbillCreateIp();
        // 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
//        String notify_url = "https://www.zzzsyh.com/cs_pay/wxpay/notify";
        String trade_type = "JSAPI";

        // ---必须参数
        // 商户号
        String mch_id = partner;
        // 随机字符串
        String nonce_str = StringUtils.getNonceStr();

        // 商品描述根据情况修改
        String body = tpWxPayDto.getBody();

        // 商户订单号
        String out_trade_no = orderId;

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", appIdApplet);
        packageParams.put("attach", attach);
        packageParams.put("body", body);
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);

        packageParams.put("notify_url", notifyUrlServiceOrderFixdraw);
        packageParams.put("openid", openId);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("total_fee", totalFee);
        packageParams.put("trade_type", trade_type);


        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(appIdApplet, appSecretApplet, partnerKey);

        String sign = reqHandler.createSign(packageParams);
        logger.info("第一次签名------------------------------" + sign);
        String xml = "<xml>" + "<appid>" + appIdApplet + "</appid>" + "<mch_id>"
                + mch_id + "</mch_id>" + "<nonce_str>" + nonce_str
                + "</nonce_str>" + "<sign>" + sign + "</sign>"
                + "<body><![CDATA[" + body + "]]></body>"
                + "<out_trade_no>" + out_trade_no
                + "</out_trade_no>" + "<attach>" + attach + "</attach>"
                + "<total_fee>" + totalFee + "</total_fee>"
                + "<spbill_create_ip>" + spbill_create_ip
                + "</spbill_create_ip>" + "<notify_url>" + notifyUrlServiceOrderFixdraw
                + "</notify_url>" + "<trade_type>" + trade_type
                + "</trade_type>" + "<openid>" + openId + "</openid>"
                + "</xml>";
        String prepay_id = "";
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";


        prepay_id = new GetWxOrderno().getPayNo(createOrderURL, xml);

        logger.info("获取到的预支付ID：" + prepay_id);


        //获取prepay_id后，拼接最后请求支付所需要的package

        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        String packages = "prepay_id=" + prepay_id;
        finalpackage.put("appId", appIdApplet);
        finalpackage.put("timeStamp", timestamp);
        finalpackage.put("nonceStr", nonce_str);
        finalpackage.put("package", packages);
        finalpackage.put("signType", "MD5");
        //要签名
        String finalsign = reqHandler.createSign(finalpackage);
        logger.info("第二次签名------------------------------" + finalsign);
        String finaPackage = "\"appId\":\"" + appIdApplet + "\",\"timeStamp\":\"" + timestamp
                + "\",\"nonceStr\":\"" + nonce_str + "\",\"package\":\""
                + packages + "\",\"signType\" : \"MD5" + "\",\"paySign\":\""
                + finalsign + "\"";

        logger.info("V3 jsApi package:" + finaPackage);
        return finaPackage;
    }

    /**
     * 微信登录——第一步：获取code
     * 注意每个用户只用授权一次，不用重复授权，授权之后就可以获取相关的用户信息
     * @param response
     */
    @RequestMapping(value = "/wechat/login")
    public void wechatLogin(HttpServletResponse response, HttpServletRequest request)throws Exception {
        String key = request.getParameter("key");
        try {
                String url = authorizationUrlWx + "%3fkey%3d" + key;
                String qrconnect = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appIdWx + "&redirect_uri=" + url + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                logger.info("info---------------------------------------------------------qrconnect:" + qrconnect);
                response.sendRedirect(qrconnect);
        } catch (Exception e) {
            e.printStackTrace();
            StringBuilder loginPage = new StringBuilder();
            loginPage.append(wxQrcodeUrl + "/indexWx.html#/"+key);
            response.sendRedirect(loginPage.toString());
        }
    }

    /**
     * 微信登录——第二步：通过code换取access_token
     *
     * @param code
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/wechat/callback")
    public void wechatCallback(@RequestParam String code, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String key = request.getParameter("key");
        String factory = request.getParameter("factory");
        try {
            logger.info("info---------------------------------------------------------factory:" + factory);
            if (EmptyUtils.isEmpty(factory) || "null".equals(factory)) {
                factory = "0";
            }
            System.out.println(key + "------------------------------------------");
            String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appIdWx + "&secret=" + appSecretWx + "&code=" +
                    code + "&grant_type=authorization_code";
            logger.info("info---------------------------------------------------------accessTokenUrl:" + accessTokenUrl);
            response.setContentType("text/html;charset=utf-8");
            String json = UrlUtils.loadURL(accessTokenUrl);
            logger.info("info---------------------------------------------------------json:" + json);
            System.out.println("json:" + json);
            Map<String, Object> wechatToken = JSON.parseObject(json, Map.class);
            System.out.println("wechatToken-----------------------------------" + wechatToken);
            System.out.println("openid-----------------------------------" + wechatToken.get("openid").toString());
            System.out.println("access_token-----------------------------------" + wechatToken.get("access_token").toString());
            //验证数据库是否存在该用户
            String token = "";

            //返回前端处理
            StringBuilder loginPage = new StringBuilder();
            loginPage.append(wxQrcodeUrl + "/indexWx.html#/"+key);
            loginPage.append("?openid=" + wechatToken.get("openid").toString());
            loginPage.append("&key=" + key);
            response.sendRedirect(loginPage.toString());
        }catch (Exception e){
            e.printStackTrace();
            StringBuilder loginPage = new StringBuilder();
            loginPage.append(wxQrcodeUrl + "/indexWx.html#/"+key);
            response.sendRedirect(loginPage.toString());
        }

    }

    /**
     * 获取微信签名  /repair
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getWechatSignRepair")
    @ResponseBody
    public Map<String, Object> getWechatSignRepair(HttpServletRequest request) throws Exception {
        /* 返回的json数据 */
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        // 1.获取参数
        String url = request.getParameter("url");
        if (url == null) {
            return jsonMap;
        } else {
            WxAccessToken wxAccessToken =  wxAccessTokenUtils.getWxAccessTokenOfRepair(appIdWx, appSecretWx, redisUtil);
//            String  accessToken =getAccessToken(appId, appSecret);
            String accessToken = wxAccessToken.getAccessToken();
            String ticket = wxAccessTokenUtils.getTicket(accessToken);
            Long timestamp = System.currentTimeMillis() / 1000;
            String nonceStr = StringUtils.getNonceStr();
            String sign = StringUtils.getSign(ticket, nonceStr, timestamp, url);
            jsonMap.put("result", "1");
            jsonMap.put("timestamp", timestamp);
            jsonMap.put("nonceStr", nonceStr);
            jsonMap.put("appId", appIdWx);
            jsonMap.put("sign", sign);
        }
        return jsonMap;
    }
}
